package net.gyapp.markim.module.contact;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.easyder.wrapper.base.view.WrapperStatusActivity;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.ImManager;
import net.gyapp.markim.core.ImPrivateUtils;
import net.gyapp.markim.core.entity.ConversationEntity;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.AccountChanged;
import net.gyapp.markim.module.basic.event.AccountIml;
import net.gyapp.markim.module.basic.event.GroupChanged;
import net.gyapp.markim.module.basic.event.GroupIml;
import net.gyapp.markim.module.collect.UserIntroduceActivity;
import net.gyapp.markim.module.contact.adapter.GroupUserAdapter;
import net.gyapp.markim.module.contact.vo.GroupInfoVo;
import net.gyapp.markim.module.contact.vo.GroupMemberVo;
import net.gyapp.markim.module.contact.vo.GroupStatusVo;
import net.gyapp.markim.module.contact.vo.QuitGroupVo;
import net.gyapp.markim.module.contact.vo.TempGroupBean;
import net.gyapp.markim.module.contact.vo.UserVo;
import net.gyapp.markim.module.mine.AlertTipsDialog;
import net.gyapp.markim.utils.RequestParams;
import net.gyapp.markim.widget.NoScrollGridLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.winds.widget.usage.TitleView;

/**
 * Auther:  winds
 * Email:   heardown@163.com
 * Date:    2018/8/3.
 * Desc:
 */

public class GroupDetailsActivity extends WrapperStatusActivity<CommonPresenter> {

    ConversationEntity entity;
    @BindView(R.id.tv_manager_num)
    TextView tvManagerNum;
    @BindView(R.id.rv_group_manage)
    RecyclerView rvGroupManage;
    @BindView(R.id.tv_member_num)
    TextView tvMemberNum;
    @BindView(R.id.rv_group_member)
    RecyclerView rvGroupMember;
    @BindView(R.id.tv_small_project)
    TextView tvSmallProject;
    @BindView(R.id.tv_group_name)
    TextView tvGroupName;
    @BindView(R.id.tv_group_qr)
    ImageView tvGroupQr;
    @BindView(R.id.tv_group_notice)
    TextView tvGroupNotice;
    @BindView(R.id.tv_set_manager)
    TextView tvSetManager;
    @BindView(R.id.tv_set_banned)
    TextView tvSetBanned;
    @BindView(R.id.tv_set_keywords)
    TextView tvSetKeywords;
    @BindView(R.id.btn_confirm)
    Button btnConfirm;

    @BindView(R.id.layout_group_project)
    LinearLayout layoutGroupProject;
    @BindView(R.id.layout_group_name)
    LinearLayout layoutGroupName;
    @BindView(R.id.layout_group_qr)
    LinearLayout layoutGroupQr;
    @BindView(R.id.layout_group_notice)
    LinearLayout layoutGroupNotice;
    @BindView(R.id.layout_keyword_shield)
    LinearLayout layoutKeywordShield;
    @BindView(R.id.iv_msg_switcher)
    ImageView ivMsgSwitcher;
    @BindView(R.id.iv_collect_switcher)
    ImageView ivCollectSwitcher;

    GroupUserAdapter userAdapter;
    GroupUserAdapter managerAdapter;
    boolean isGroupManager;

    public final static int SIGN_ADD_GROUP = 10001;
    public final static int SIGN_DELETE_GROUP = 10002;

    public static Intent getIntent(Context context, ConversationEntity entity) {
        return new Intent(context, GroupDetailsActivity.class).putExtra("entity", entity);
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_group_details;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        super.initView(savedInstanceState, titleView, intent);
        titleView.setCenterText("群组详情");
        entity = (ConversationEntity) intent.getSerializableExtra("entity");
        tvGroupName.setText(entity.name);

        rvGroupMember.setLayoutManager(new NoScrollGridLayoutManager(mActivity, 4));
        userAdapter = new GroupUserAdapter();
        rvGroupMember.setAdapter(userAdapter);

        rvGroupManage.setLayoutManager(new NoScrollGridLayoutManager(mActivity, 4));
        managerAdapter = new GroupUserAdapter();
        rvGroupManage.setAdapter(managerAdapter);

        rvGroupMember.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Object item = userAdapter.getItem(position);
                if (item instanceof GroupMemberVo.GroupUsersBean) {
                    UserVo userVo = new UserVo();
                    userVo.userInfo = new UserVo.UserInfoBean();
                    userVo.userInfo.userId = ((GroupMemberVo.GroupUsersBean) item).userId;
                    userVo.userInfo.userName = ((GroupMemberVo.GroupUsersBean) item).userInfo.userName;
                    userVo.userInfo.userNumber = ((GroupMemberVo.GroupUsersBean) item).userInfo.userNumber;
                    userVo.userInfo.nick = ((GroupMemberVo.GroupUsersBean) item).userInfo.nick;
                    userVo.userInfo.phone = ((GroupMemberVo.GroupUsersBean) item).userInfo.phone;
                    userVo.userInfo.userAvatar = ((GroupMemberVo.GroupUsersBean) item).userInfo.userAvatar;

                    startActivity(UserIntroduceActivity.getIntent(mActivity, userVo));
                } else if (item instanceof TempGroupBean) {
                    TempGroupBean bean = (TempGroupBean) item;
                    if (bean.type == 1) {
                        //添加群聊
                        startActivityForResult(InviteGroupActivity.getIntent(mActivity, entity.sessionIdStr, memberList == null ? new ArrayList<GroupMemberVo.GroupUsersBean>() : memberList), SIGN_ADD_GROUP);
                    } else if (bean.type == 2) {
                        startActivityForResult(RemoveGroupActivity.getIntent(mActivity, entity.sessionIdStr, memberList == null ? new ArrayList<GroupMemberVo.GroupUsersBean>() : memberList), SIGN_DELETE_GROUP);
                    }
                }
            }
        });
        rvGroupManage.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Object item = managerAdapter.getItem(position);
                if (item instanceof GroupMemberVo.GroupUsersBean) {
                    UserVo userVo = new UserVo();
                    userVo.userInfo = new UserVo.UserInfoBean();
                    userVo.userInfo.userId = ((GroupMemberVo.GroupUsersBean) item).userId;
                    userVo.userInfo.userName = ((GroupMemberVo.GroupUsersBean) item).userInfo.userName;
                    userVo.userInfo.userNumber = ((GroupMemberVo.GroupUsersBean) item).userInfo.userNumber;
                    userVo.userInfo.nick = ((GroupMemberVo.GroupUsersBean) item).userInfo.nick;
                    userVo.userInfo.phone = ((GroupMemberVo.GroupUsersBean) item).userInfo.phone;
                    userVo.userInfo.userAvatar = ((GroupMemberVo.GroupUsersBean) item).userInfo.userAvatar;

                    startActivity(UserIntroduceActivity.getIntent(mActivity, userVo));
                }
            }
        });

    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        getGroupUser(entity.sessionIdStr);
        getGroupInfo(entity.sessionIdStr);
        getGroupShieldStatus(entity.sessionIdStr);
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if (url.contains(ApiConfig.API_GET_GROUP_INFO)) {
            processGroupInfo((GroupInfoVo) dataVo);
        } else if (url.contains(ApiConfig.API_GET_GROUP_USERS)) {
            processGroupMember((GroupMemberVo) dataVo);
        } else if (url.contains(ApiConfig.API_COLLECTION)) {
            ivCollectSwitcher.setSelected(true);
        } else if (url.contains(ApiConfig.API_CANCEL_COLLECTION)) {
            ivCollectSwitcher.setSelected(false);
        } else if (url.contains(ApiConfig.API_SET_SHIELD_GROUP_STATUS)) {
            ivMsgSwitcher.setSelected((((GroupStatusVo) dataVo).status) == 1);
        } else if (url.contains(ApiConfig.API_GET_SHIELD_GROUP_STATUS)) {
            ivMsgSwitcher.setSelected((((GroupStatusVo) dataVo).status) == 1);
        } else if (url.contains(ApiConfig.API_QUIT_GROUP)) {
            processQuitGroup();
        }
        super.showContentView(url, dataVo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SIGN_ADD_GROUP || requestCode == SIGN_DELETE_GROUP) {
            showLoadingStatus();
            getGroupUser(entity.sessionIdStr);
            getGroupInfo(entity.sessionIdStr);
        }
    }

    @OnClick({R.id.btn_confirm, R.id.layout_group_project, R.id.layout_group_name, R.id.layout_group_qr,
            R.id.layout_group_notice, R.id.layout_keyword_shield, R.id.iv_msg_switcher, R.id.iv_collect_switcher,
            R.id.layout_clear_cache, R.id.layout_group_member, R.id.layout_banned})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_confirm:
                showQuitTips();
                break;
            case R.id.layout_group_project: //小程序
                if (isGroupManager) {
                    startActivity(ProjectSetActivity.getIntent(mActivity, entity,
                            infoVo != null ? infoVo.groupInfo.groupTitle : null, infoVo != null ? infoVo.groupInfo.groupTitleUrl : null));
                } else {
                    showToast("您不是管理员，暂无权限修改");
                }
                break;
            case R.id.layout_group_name: //群名称
                if (isGroupManager) {
                    startActivity(GroupNameActivity.getIntent(mActivity, entity.sessionIdStr, infoVo != null ? infoVo.groupInfo.groupName : ""));
                } else {
                    showToast("您不是管理员，暂无权限修改");
                }
                break;
            case R.id.layout_group_qr:
                startActivity(GroupQrActivity.getIntent(mActivity, entity, infoVo != null ? infoVo.groupInfo.groupQrUrl : ""));
                break;
            case R.id.layout_group_notice: //群公告
                startActivity(GroupNoticeActivity.getIntent(mActivity, entity.sessionIdStr, infoVo != null ? infoVo.groupInfo.groupNotice : null, isGroupManager));
                break;
            case R.id.layout_keyword_shield: //关键词屏蔽
                if (isGroupManager) {
                    startActivity(KeywordShieldActivity.getIntent(mActivity, entity.sessionIdStr));
                } else {
                    showToast("您不是管理员，暂无权限修改");
                }
                break;
            case R.id.iv_msg_switcher:
                setGroupShieldStatus(entity.sessionIdStr);
                break;
            case R.id.iv_collect_switcher:
                boolean selected = ivCollectSwitcher.isSelected();
                if (selected) {
                    cancelCollect(entity.sessionIdStr);
                } else {
                    collectUser(entity.sessionIdStr);
                }
                break;
            case R.id.layout_clear_cache:
                clearCache(entity.id);
                break;
            case R.id.layout_group_member:
                if (memberList != null) {
                    startActivity(GroupMemberActivity.getIntent(mActivity, memberList, "全部群成员"));
                }
                break;
            case R.id.layout_banned: //禁言
                if (bannedList == null) {
                    bannedList = new ArrayList<>();
                }
                startActivity(GroupMemberActivity.getIntent(mActivity, bannedList, "禁言"));
                break;
        }
    }

    @Subscribe
    public void groupChanged(GroupChanged changed) {
        if (changed.sign == GroupIml.SIGN_PROJECT_CHANGED || changed.sign == GroupIml.SIGN_NOTICE_CHANGED) {
            getGroupInfo(entity.sessionIdStr, true);
        } else if (changed.sign == GroupIml.SIGN_NAME_CHANGED) {
            getGroupInfo(entity.sessionIdStr, true);
        }
    }

    GroupInfoVo infoVo;

    private void processGroupInfo(final GroupInfoVo dataVo) {
        this.infoVo = dataVo;
        ivCollectSwitcher.setSelected(dataVo.groupInfo.collection);
        tvGroupName.setText(dataVo.groupInfo.groupName);
        tvGroupNotice.setText(dataVo.groupInfo.groupNotice);

//        if (!TextUtils.isEmpty(dataVo.groupInfo.groupName) && !entity.name.equals(dataVo.groupInfo.groupName)) {
        //名称不一致  通知修改名称
        entity.name = dataVo.groupInfo.groupName;
        entity.avatar = dataVo.groupInfo.groupAvatar;
        TaskScheduler.execute(new Runnable() {
            @Override
            public void run() {
                ImPrivateUtils.updateGroupName(entity, dataVo.groupInfo.groupName, dataVo.groupInfo.groupAvatar);
            }
        });
//        }

    }

    /**
     * 获取群成员信息
     *
     * @param groupNumber
     */
    private void getGroupUser(String groupNumber) {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_GROUP_USERS, new RequestParams().put("groupNumber", groupNumber).get(), GroupMemberVo.class);
    }

    ArrayList<GroupMemberVo.GroupUsersBean> memberList;
    ArrayList<GroupMemberVo.GroupUsersBean> bannedList;

    private void processGroupMember(GroupMemberVo dataVo) {
        List<GroupMemberVo.GroupUsersBean> managerList = new ArrayList<>();
        memberList = new ArrayList<>();
        bannedList = new ArrayList<>();

        if (dataVo.groupUsers.groupUsers != null) {
            memberList.addAll(dataVo.groupUsers.groupUsers);
        }

        if (dataVo.groupUsers.silenceUsers != null) {
            bannedList.addAll(dataVo.groupUsers.silenceUsers);
        }

        if (dataVo.groupUsers.adminUsers != null) {
            for (int i = 0; i < dataVo.groupUsers.adminUsers.size(); i++) {
                GroupMemberVo.GroupUsersBean bean = dataVo.groupUsers.adminUsers.get(i);
                if (ImHelper.isSelf(bean.userInfo.userName)) {
                    isGroupManager = true;
                }

            }
            managerList.addAll(dataVo.groupUsers.adminUsers);
        }
//        btnConfirm.setText(isGroupManager ? "解散本群" : "退出群聊");
        btnConfirm.setText("退出群聊");
        managerAdapter.setAdapterData(managerList, false, false);
        userAdapter.setAdapterData(memberList, true, isGroupManager);
        tvManagerNum.setText(String.format("%1$s%2$s%3$s", "管理员(", managerList.size(), "人)"));
        tvMemberNum.setText(String.format("%1$s%2$s%3$s", "全部群成员(", memberList.size(), "人)"));
    }

    private void clearCache(final long conversationId) {
        showLoadingView();
        TaskScheduler.execute(new Task<Boolean>() {
            @Override
            public Boolean doInBackground() throws InterruptedException {
                ImHelper.deleteMessageEntity(conversationId);
                return true;
            }

            @Override
            public void onSuccess(Boolean result) {
                onStopLoading();
                showToast("清除成功");
            }
        });
    }

    private void collectUser(String userId) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_COLLECTION, new RequestParams()
                .put("collectionId", userId)
                .put("type", 1)
                .get(), BaseVo.class);
    }

    private void cancelCollect(String userId) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_CANCEL_COLLECTION,
                new RequestParams()
                        .put("collectionId", userId)
                        .get(),
                BaseVo.class);
    }

    /**
     * 获取群信息
     *
     * @param groupNumber
     */
    private void getGroupInfo(String groupNumber) {
        getGroupInfo(groupNumber, false);
    }

    /**
     * 获取群信息
     *
     * @param groupNumber
     */
    private void getGroupInfo(String groupNumber, boolean showProgress) {
        presenter.setNeedDialog(showProgress);
        presenter.postData(ApiConfig.API_GET_GROUP_INFO, new RequestParams().put("groupNumber", groupNumber).get(), GroupInfoVo.class);
    }

    /**
     * 获取群申请信息
     */
    private void getGroupVerifyInfo() {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_GROUP_VERIFY_INFO, BaseVo.class);
    }

    /**
     * 获取群屏蔽状态
     *
     * @param groupId
     */
    private void getGroupShieldStatus(String groupId) {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_SHIELD_GROUP_STATUS, new RequestParams().put("groupId", groupId).get(), GroupStatusVo.class);
    }

    /**
     * 设置群屏蔽
     *
     * @param groupId
     */
    private void setGroupShieldStatus(String groupId) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_SET_SHIELD_GROUP_STATUS, new RequestParams().put("groupId", groupId).get(), GroupStatusVo.class);
    }


    /**
     * 获取群小程序
     *
     * @param groupNumber
     */
    private void getGroupProject(String groupNumber) {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_SMALL_PROGRAM, new RequestParams().put("groupNumber", groupNumber).get());
    }

    /**
     * 设置群小程序
     *
     * @param groupNumber
     * @param groupTitle
     * @param groupTitleUrl
     */
    private void setGroupProject(String groupNumber, String groupTitle, String groupTitleUrl) {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_SMALL_PROGRAM, new RequestParams().put("groupNumber", groupNumber).put("groupTitle", groupTitle).put("groupTitleUrl", groupTitleUrl).get());
    }

    /**
     * 更新群通知
     *
     * @param groupNumber
     * @param groupNotice
     */
    private void updateGroupNotice(String groupNumber, String groupNotice) {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_SMALL_PROGRAM, new RequestParams().put("groupNumber", groupNumber).put("groupNotice", groupNotice).get());
    }

    /**
     * 同意入群
     *
     * @param groupUsersId
     */
    private void setAgreeEntryGroup(String groupUsersId) {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_AGREE_USER_ENTRY_GROUP, new RequestParams().put("groupUsersId", groupUsersId).get());
    }

    /**
     * 拒绝入群
     *
     * @param groupUsersId
     */
    private void setRefuseEntryGroup(String groupUsersId) {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_AGREE_USER_ENTRY_GROUP, new RequestParams().put("groupUsersId", groupUsersId).get());
    }

    private void showQuitTips() {
        new AlertTipsDialog(mActivity).setUp(new AlertTipsDialog.OnConfirmListener() {
            @Override
            public void onConfirm(Dialog dialog, View view) {
                dialog.dismiss();
                quitGroup();
            }
        }, "退出群聊将清空聊天记录且不可恢复，请谨慎操作", "退出", "取消").show();
    }

    private void quitGroup() {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_QUIT_GROUP, new RequestParams().put("groupNumber", entity.sessionIdStr).get(), QuitGroupVo.class);
    }

    private void processQuitGroup() {
        deleteGroup(entity);
    }

    private void deleteGroup(final ConversationEntity entity) {
        showLoadingView();
        TaskScheduler.execute(new Task<Boolean>() {
            @Override
            public Boolean doInBackground() throws InterruptedException {
                ImPrivateUtils.clearCache(entity.id);
//                ImHelper.deleteGroup(entity.sessionIdStr);
                ImManager.getInstance().retryAutoLogin();
                return true;
            }

            @Override
            public void onSuccess(Boolean result) {
                onStopLoading();
                showToast("退出成功");
                EventBus.getDefault().post(new AccountChanged(AccountIml.ACCOUNT_CONTACT_QUIT_GROUP));
                finish();
            }
        });
    }
}
